package frog.lazy.framework.core.tools;


import frog.lazy.framework.core.dto.TreeDTO;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TreeUtil {

    public static <T extends TreeDTO> List<T> listToTree(List<T> list){
        Map<Long, T> mapTmp = new HashMap<>();
        for (T current : list) {
            mapTmp.put(current.getId(), current);
        }
        List<T> finalList = new ArrayList<>();

        mapTmp.forEach((k, v) -> {
            if(v.getPid() == null || v.getPid().compareTo(0L) == 0) {
                finalList.add(v);
            } else {
                T pt = mapTmp.get(v.getPid());
                if(null != pt) {
                    mapTmp.get(v.getPid()).getChildren().add(v);
                }else {
                    finalList.add(v);
                }

            }
        });
        return finalList;
    }
}
